/**
 * Copyright (C) 2010 Sergey Grigoriev <s.a.grigoriev@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.gmf.core

import com.google.inject.Guice
import com.google.inject.Inject
import com.google.inject.Injector
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.maven.artifact.handler.ArtifactHandler
import org.apache.maven.artifact.repository.ArtifactRepository
import org.apache.maven.artifact.resolver.ArtifactResolver
import org.apache.maven.project.MavenProject
import org.codehaus.groovy.runtime.InvokerHelper

/**
 * Responsible for initialization of the application.
 */
class Bootstrapper {
  /**
   *  Maven project scoped injectors
   */
  private Map<MavenProject, Injector> injectors = Collections.synchronizedMap(new LinkedHashMap<MavenProject, Injector>())

  private final Logger log = Logger.getLogger(getClass())

  /**
   * Maven artifact resolver cannot resolve attached artifacts unless they are in repository.
   * This set contains attached artifacts
   */
  private final Set attachedArtifacts = Collections.synchronizedSet(new LinkedHashSet())

  @Inject
  private FlexSdkFacade flexSdkFacade

  /**
   * The root injector has nothing project-specific, injects global scope objects only
   */
  Injector injector

  synchronized void initialize(
    ArtifactHandler swfArtifactHandler,
    ArtifactHandler swcArtifactHandler,
    ArtifactResolver artifactResolver,
    ArtifactRepository localRepository,
    List remoteRepositories)
  {

    if (injector) return

    injector = Guice.createInjector(new CoreModule(log, attachedArtifacts,swfArtifactHandler,swcArtifactHandler,artifactResolver,localRepository, remoteRepositories))
    injector.injectMembers(this)
    flexSdkFacade.injector = injector

    def groovyVersion = InvokerHelper.getVersion()
    log.info("Using Groovy runtime version $groovyVersion")

    def logLevel = System.properties['logLevel'] ?: 'info'
    logLevel = logLevel.toUpperCase()
    Logger.rootLogger.level = Level."${logLevel}"
    MavenProject.metaClass.getGmfInjector = { injectors[delegate] }
    MavenProject.metaClass.setGmfInjector = { injectors[delegate] = it }

    log.debug 'finished initialization'
  }
}
